import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useEffect } from 'react';
import { Button, Modal, Input, Table, Space, Form, Pagination, Select, Radio, Image, Upload, DatePicker, UploadProps, DatePickerProps, TreeSelect, Switch, Tabs } from 'antd';
import { WomanOutlined, ManOutlined, PlusOutlined, InboxOutlined, PaperClipOutlined } from '@ant-design/icons';
import SmartMap from '../smart-map';
import systemApi from '../../api/system';
import * as XLSX from "xlsx";
import { commonErrorMsg, commonSuccessMsg, deepCopy, generateTreeData, getChangeEventValue, handleDownloadByName, isEmpty, makeClassNameList, toastShort } from '../../utils';
import LoadingWapper from '../loading/LoadingWapper';
import { BJHSpeciesInfoType, RoleType, SpeciesInfoType, UserType } from '../../utils/types';
import statisticalAnalysisTools from '../../statistical-analysis-temp/src';
import { setSystemConfig } from '../../redux/system.slice';
import redux from './../../redux/store';
import type { RcFile } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';

interface Props {
    onFinish?: Function
};


const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });


const FeedBackModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }));

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [form] = Form.useForm<UserType>();
    const [formData, setFormData] = useState<UserType>({});
    const [options, setOptions] = useState([
        {
            value: '1',
            label: '问题反馈',
        },
        {
            value: '2',
            label: '优化建议',
        },
    ])
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([
    ]);
    const delayTimer = useRef(null);

    useEffect(() => {
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current)
        }
    }, [])

    const handleConfirm = async () => {
        try {
            const values = await form.validateFields();
            setSubmitLoading(true)
            delayTimer.current = setTimeout(() => {
                toastShort('success', '提交成功，您的反馈会被尽快处理！');
                setIsModalOpen(false);
                setSubmitLoading(false)
            }, 1000);
        } catch (e) {
            console.log("e", e)
        }
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        setFileList([]);
        form.setFieldValue('type', null);
        form.setFieldValue('title', null);
        form.setFieldValue('desc', null);
        form.setFieldValue('nickName', null);
        form.setFieldValue('phone', null);
    }

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };

    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
        setFileList(newFileList);

    const openModal = () => {
        setIsModalOpen(true);
        let tempUserInfo: UserType = redux.getState().systemConfig.userInfo;
        console.log("tempUserInfo--->", tempUserInfo)
        setFormData(tempUserInfo);
        const { keys, values } = Object;
        const keyList = keys(tempUserInfo);
        const valueList = values(tempUserInfo)
        keyList.forEach((key, index) => {
            form.setFieldValue(key, valueList[index] ? valueList[index] : null)
        })
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传</div>
        </div>
    );
    return (
        <Modal
            title={'问题反馈'}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={'800px'}
            maskClosable={false}
            confirmLoading={submitLoading}
            destroyOnClose
            centered
        >
            <div className='custom-modal-container'>
                <Form
                    form={form}
                    labelCol={{
                        span: 4
                    }}
                    style={{ marginRight: 42, width: 672 }}
                >
                    <Form.Item
                        name="type"
                        label="反馈类型"
                        required={true}
                        rules={[{ required: true, message: "请选择反馈类型" }]}
                    >
                        <Select
                            options={options}
                            placeholder={'请选择反馈类型'}
                        />
                    </Form.Item>
                    <Form.Item
                        name="title"
                        label="标题"
                        rules={[{ required: true, message: "请输入反馈标题" }]}
                    >
                        <Input
                            placeholder='请输入反馈标题'
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item
                        name="desc"
                        label="详细描述"
                        rules={[{ required: true, message: "请输入问题详细描述" }]}
                    >
                        <Input.TextArea
                            placeholder='请输入问题详细描述(最多不超过200字)'
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item
                        name="imageList"
                        label="反馈截图"
                    >
                        <Upload
                            action="https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChange}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="nickName"
                        label="提交人"
                    >
                        <Input
                            placeholder=''
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item
                        name="phone"
                        label="联系方式"
                    >
                        <Input
                            placeholder='请输入联系方式(电话或邮件)'
                            allowClear
                        />
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    )
}

export default forwardRef(FeedBackModal)